package com.sky.service.impl;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.sky.constant.MessageConstant;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.exception.LoginFailedException;
import com.sky.mapper.UserMapper;
import com.sky.properties.WeChatProperties;
import com.sky.service.UserService;
import com.sky.utils.HttpClientUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private WeChatProperties weChatProperties;

    private static final String WX_GET_OPENID_URL = "https://api.weixin.qq.com/sns/jscode2session";

    /**
     * 用户登录
     * @param userLoginDTO 里面包含微信授权码
     * @return 用户信息
     * 业务逻辑分析
     * 1.根据授权码拿到openid
     * 2.如果没有openid直接抛业务异常
     * 3.根据openid查询用户
     * 4.如果用户不存在说明第一次登录,将用户添加到表中
     * 5.返回用户信息
     */
    @Override
    public User login(UserLoginDTO userLoginDTO) {
        //1.根据授权码拿到openid
        String openid = getOpenid(userLoginDTO.getCode());
        //2.如果没有openid直接抛业务异常
        if (openid == null){
            throw new LoginFailedException(MessageConstant.LOGIN_FAILED);
        }
        //3.根据openid查询用户
        User user = userMapper.findByOpenid(openid);
        //4.如果用户不存在说明第一次登录,将用户添加到表中
        if (user == null){
            //新建用户
            user = User.builder()
                    .openid(openid)
                    .createTime(LocalDateTime.now())
                    .build();
            //添加到用户表中,并且返回主键
            userMapper.add(user);
        }
        //5.返回用户信息
        return user;
    }

    /**
     * 根据微信授权码获取openid
     * @param code
     * @return
     */
    private String getOpenid(String code) {
        try {
            //封装请求信息
            HashMap<String, String> paramMap = new HashMap<>();
            paramMap.put("appid",weChatProperties.getAppid());
            paramMap.put("secret",weChatProperties.getSecret());
            paramMap.put("js_code",code);
            paramMap.put("grant_type","authorization_code");
            //拿到的是json字符串
            String jsonStr = HttpClientUtil.doGet(WX_GET_OPENID_URL, paramMap);
            //将字符串转换成Map
            Map map = new ObjectMapper().readValue(jsonStr, Map.class);
            //拿到openid
            return (String) map.get("openid");
        } catch (JsonProcessingException ex) {
            //catch到异常直接return null
            System.err.println(ex.getMessage());
            return null;
        }
    }
}
